#!/usr/bin/env python3
"""
IndexTTS2 守护进程启动器
支持Windows下的后台运行和进程管理
"""

import os
import sys
import time
import signal
import subprocess
import threading
from pathlib import Path
import psutil
import json

class TTSDaemon:
    def __init__(self):
        self.project_dir = Path(__file__).parent.absolute()
        self.pid_file = self.project_dir / "tts_daemon.pid"
        self.log_file = self.project_dir / "tts_daemon.log"
        self.process = None
        
    def is_running(self):
        """检查服务是否已在运行"""
        if not self.pid_file.exists():
            return False
            
        try:
            with open(self.pid_file, 'r') as f:
                pid = int(f.read().strip())
            
            # 检查进程是否存在
            return psutil.pid_exists(pid)
        except:
            return False
    
    def start(self):
        """启动TTS服务"""
        if self.is_running():
            print("TTS服务已在运行中")
            return False
        
        print("正在启动TTS服务...")
        
        # 设置环境变量
        env = os.environ.copy()
        env['GRADIO_ANALYTICS_ENABLED'] = 'False'
        
        # 构建启动命令
        if sys.platform == "win32":
            # Windows下使用pythonw.exe
            python_exe = sys.executable.replace("python.exe", "pythonw.exe")
            if not Path(python_exe).exists():
                python_exe = "pythonw.exe"
        else:
            python_exe = sys.executable
        
        cmd = [
            python_exe,
            "webui.py",
            "--fp16",
            "--host", "127.0.0.1", 
            "--port", "7863"
        ]
        
        try:
            # 启动进程
            if sys.platform == "win32":
                # Windows下创建新的进程组
                self.process = subprocess.Popen(
                    cmd,
                    cwd=self.project_dir,
                    env=env,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                    stdin=subprocess.DEVNULL,
                    creationflags=subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW
                )
            else:
                # Unix系统下
                self.process = subprocess.Popen(
                    cmd,
                    cwd=self.project_dir,
                    env=env,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                    stdin=subprocess.DEVNULL,
                    start_new_session=True
                )
            
            # 保存PID
            with open(self.pid_file, 'w') as f:
                f.write(str(self.process.pid))
            
            # 等待一下确保启动成功
            time.sleep(3)
            
            if self.process.poll() is None:
                print(f"✅ TTS服务启动成功! PID: {self.process.pid}")
                print(f"📱 访问地址: http://127.0.0.1:7863")
                return True
            else:
                print("❌ TTS服务启动失败")
                self.pid_file.unlink(missing_ok=True)
                return False
                
        except Exception as e:
            print(f"❌ 启动失败: {e}")
            return False
    
    def stop(self):
        """停止TTS服务"""
        if not self.is_running():
            print("TTS服务未在运行")
            return True
        
        try:
            with open(self.pid_file, 'r') as f:
                pid = int(f.read().strip())
            
            print(f"正在停止TTS服务 (PID: {pid})...")
            
            # 终止进程
            if sys.platform == "win32":
                os.system(f"taskkill /PID {pid} /F /T")
            else:
                os.kill(pid, signal.SIGTERM)
            
            # 等待进程结束
            for i in range(10):
                if not psutil.pid_exists(pid):
                    break
                time.sleep(1)
            
            # 强制终止（如果还在运行）
            if psutil.pid_exists(pid):
                if sys.platform == "win32":
                    os.system(f"taskkill /PID {pid} /F")
                else:
                    os.kill(pid, signal.SIGKILL)
            
            # 清理PID文件
            self.pid_file.unlink(missing_ok=True)
            print("✅ TTS服务已停止")
            return True
            
        except Exception as e:
            print(f"❌ 停止失败: {e}")
            return False
    
    def restart(self):
        """重启TTS服务"""
        print("正在重启TTS服务...")
        self.stop()
        time.sleep(2)
        return self.start()
    
    def status(self):
        """查看服务状态"""
        if self.is_running():
            with open(self.pid_file, 'r') as f:
                pid = int(f.read().strip())
            print(f"✅ TTS服务正在运行 (PID: {pid})")
            print(f"📱 访问地址: http://127.0.0.1:7863")
            return True
        else:
            print("❌ TTS服务未运行")
            return False

def main():
    """主函数"""
    daemon = TTSDaemon()
    
    if len(sys.argv) < 2:
        print("用法:")
        print("  python daemon_runner.py start   - 启动服务")
        print("  python daemon_runner.py stop    - 停止服务") 
        print("  python daemon_runner.py restart - 重启服务")
        print("  python daemon_runner.py status  - 查看状态")
        return
    
    command = sys.argv[1].lower()
    
    if command == "start":
        daemon.start()
    elif command == "stop":
        daemon.stop()
    elif command == "restart":
        daemon.restart()
    elif command == "status":
        daemon.status()
    else:
        print(f"未知命令: {command}")

if __name__ == "__main__":
    main()
